﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace OpenWings.Entities
{
    public class EntityList<TEntity> : List<TEntity>, IDirty where TEntity : Entity
    {
        public event EventHandler<DirtyChangedEventArgs> DirtyChanged;
        public event EventHandler<DirtyTrackingChangedEventArgs> DirtyTrackingChanged;

        bool _IsDirty;
        bool _DirtyTrackingEnabled;

        public bool DirtyTracking
        {
            get
            {
                return _DirtyTrackingEnabled;
            }
            set
            {
                if (value != _DirtyTrackingEnabled)
                {
                    _DirtyTrackingEnabled = value;
                    OnDirtyTrackingChanged(this, new DirtyTrackingChangedEventArgs(_DirtyTrackingEnabled));
                }
            }
        }

        public bool IsDirty
        {
            get
            {
                return _IsDirty;
            }
            set
            {
                if (DirtyTracking)
                    if (_IsDirty != value)
                    {
                        _IsDirty = value;
                        OnDirtyChanged(this, new DirtyChangedEventArgs(_IsDirty));
                    }
            }
        }

        public void Clean()
        {
            foreach (TEntity Entity in this)
                Entity.Clean();

            IsDirty = false;
        }

        public void OnDirtyChanged(object sender, DirtyChangedEventArgs e)
        {
            if (DirtyChanged != null)
                DirtyChanged(sender, e);
        }

        public void OnDirtyTrackingChanged(object sender, DirtyTrackingChangedEventArgs e)
        {
            foreach (TEntity Entity in this)
                Entity.DirtyTracking = e.Enabled;

            if (DirtyTrackingChanged != null)
                DirtyTrackingChanged(sender, e);
        }

        public EntityList()
            : base()
        {
        }

        public EntityList(IEnumerable<TEntity> entities)
            : base(entities)
        {
            foreach (TEntity Entity in entities)
                Entity.DirtyChanged += new EventHandler<DirtyChangedEventArgs>(OnDirtyChanged);

            // IsDirty = true ???
        }

        public new void Add(TEntity entity)
        {
            base.Add(entity);

            entity.DirtyTracking = DirtyTracking;
            entity.DirtyChanged += new EventHandler<DirtyChangedEventArgs>(OnDirtyChanged);

            entity.IsDirty = true;
        }

        public new void Remove(TEntity entity)
        {
            base.Remove(entity);

            entity.DirtyChanged -= new EventHandler<DirtyChangedEventArgs>(OnDirtyChanged);

            IsDirty = true;
        }
    }
}
